<template>
  <div :id="mapId" style="width: 100%; height: 100%;"></div>
</template>

<script lang="ts" setup>
// import { onMounted, ref } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { useDark, useStorage } from '@vueuse/core';
// 使用useDark获取暗黑模式状态
const isDark = useDark();
const caodeScgeme = ref(false)
// 监听isDark的变化
watch(isDark, (newValue) => {
  caodeScgeme.value = newValue
  // 这里可以执行其他逻辑，例如更新UI
});

const props = defineProps({
  mapId: {
    type: String,
    default: 'amap-container'
  },
  center: {
    type: Array,
    default: () => [116.397428, 39.90923]
  },
  zoom: {
    type: Number,
    default: 10
  }
});

const map = ref(null);
const loadAmap = () => {
  if (localStorage.getItem('vueuse-color-scheme')=='dark') {
    caodeScgeme.value = true;
  }else{
    caodeScgeme.value = false;
  }
  AMapLoader.load({
    key: '11184ee48ef99dc60c517f448c3a189a', // 您的高德地图API密钥
    version: '2.0', // 高德地图API版本
    plugins: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType'] // 需要使用的插件列表
  }).then((AMap) => {
    map.value = new AMap.Map(props.mapId, {
      center: props.center,
      zoom: props.zoom,
      logo: false
    });
    if (caodeScgeme.value) {
      map.value.setMapStyle('amap://styles/dark')
    }else{
      map.value.setMapStyle('amap://styles/normal')
    }
    // 添加标记
    const marker = new AMap.Marker({
      position: props.center
    });
    map.value.add(marker);
  }).catch(e => {
    // console.log('地图加载失败');
    console.error(e);
  });
}
watch(()=>caodeScgeme.value,(newValue:any,oldValue:any)=>{
  loadAmap();
},{deep: true})
watch(props, () => {
  loadAmap();
});
onMounted(() => {
  loadAmap()
});
</script>

<style scoped>
#amap-container {
  width: 100%;
  height: 100%;
}
/* 去除高德地图logo */
::v-deep .amap-logo {
  display: none;
  opacity: 0 !important;
}
::v-deep .amap-copyright {
  opacity: 0;
}
</style>
